const sq = require("../../db/mysql");

module.exports = {
  async list(page = 1, count = 10, type = "update_at", order = "DESC") {
    try {
      let data = await sq.model("product").findAndCountAll({
        order: [[type, order]],
        where: {
            is_delete: 0
        },
        limit: count,
        offset: (page - 1) * count
      });
      return { code: 200, data: data.rows };
    } catch (error) {
      console.log(error);
      return { code: 400, msg: "查找出错" };
    }
  },

  async detail(id) {
    try {
        console.log(id)
      let data = await sq.model("product").findOne({where:{ id: id }});
    
      console.log(data.dataValues)
      if(data.dataValues.is_delete == 1) {
        return {code: 400, msg: '产品已删除'};
      }

      return { code: 200, data: data.dataValues };
    } catch (error) {
      console.log(error);
      return { code: 400, msg: "查找出错" };
    }
  },

  async edit(data) {
    try {
      let id = data.id;
      delete data.id;
      let res = await sq.model("product").update(data, { where: { id: id } });
      return { code: 200, data: [] };
    } catch (error) {
      console.log(error);
      return { code: 400, msg: "查找出错" };
    }
  },

  async remove(id) {
    try {
      console.log(id);
      let res = await sq
        .model("product")
        .update({ is_delete: 1 }, { where: { id: id } });
      return { code: 200, data: [] };
    } catch (error) {
      console.log(error);
      return { code: 400, msg: "查找出错" };
    }
  },

  async add(data) {
    try {
      let res = await sq.model("product").create(data);
      return { code: 200, data: [] };
    } catch (error) {
      return { code: 400, msg: "查找出错" };
    }
  }
};
